/*MyPhotoIndex Free Photo Organizer <www.myphotoindex.com>
  Copyright (C) <2006-2009>  <Asaf Yarkoni asaf@yarkoni.net>

  This program is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program.  If not, see <http://www.gnu.org/licenses/>.*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using System.Globalization;

namespace MyPhotoIndex.Settings
{
    class MPIProperyGrid : PropertyGrid
    {
        private Control.ControlCollection m_controls;

        internal void SelectSetting(String settingToLocate)
        {
            Control propertyGridView = m_controls[2];

            Type propertyGridViewType = propertyGridView.GetType();
            FieldInfo allGridEntriesFieldInfo = propertyGridViewType.GetField("allGridEntries", BindingFlags.NonPublic | BindingFlags.FlattenHierarchy | BindingFlags.Instance);
            Object allGridEntries = allGridEntriesFieldInfo.GetValue(propertyGridView);

            Type allGridEntriesType = allGridEntries.GetType();
            FieldInfo gridEntriesFieldInfo = allGridEntriesType.GetField("entries", BindingFlags.NonPublic | BindingFlags.FlattenHierarchy | BindingFlags.Instance);
            Object entries = gridEntriesFieldInfo.GetValue(allGridEntries);

            Object[] o = (Object[])entries;
            foreach (Object entry in o)
            {
                Type entryType = entry.GetType();
                PropertyInfo propertyNameInfo = entryType.GetProperty("PropertyName", typeof(String));
                String propertyName = (String)propertyNameInfo.GetValue(entry, new object[] { });
                if (String.Compare(propertyName, settingToLocate, true, CultureInfo.InvariantCulture) == 0)
                {
                    PropertyInfo selectedGridEntryPropery = propertyGridViewType.GetProperty("SelectedGridEntry", BindingFlags.NonPublic | BindingFlags.FlattenHierarchy | BindingFlags.Instance);
                    selectedGridEntryPropery.SetValue(propertyGridView, entry, new object[] { });
                    break;
                }
            }
        }

        protected override Control.ControlCollection CreateControlsInstance()
        {
            m_controls = base.CreateControlsInstance();
            return m_controls;
        }
    }
}
